<template>
  <el-dialog
    :visible="showVisible"
    center
    :show-close="false"
    width="800px"
    :append-to-body="true"
  >
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建验证规则" : "编辑验证规则" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>

    <el-form class="pl30 pr30" :model="formData" ref="form" label-width="120px">
      <el-form-item
        label="规则编码"
        prop="ruleCode"
        :rules="[
          { required: true, message: '规则编码不能为空', trigger: 'change' },
        ]"
      >
        <el-input
          :disabled="!isNew"
          v-model="formData.ruleCode"
          style="width: 600px"
          placeholder="请输入规则编码"
          :maxlength="64"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="规则名称"
        prop="ruleName"
        :rules="[
          { required: true, message: '规则名称不能为空', trigger: 'change' },
        ]"
      >
        <el-input
          v-model="formData.ruleName"
          style="width: 600px"
          placeholder="请输入规则名称"
          :maxlength="64"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="状态"
        prop="status"
        :rules="[
          { required: true, message: '状态不能为空', trigger: 'change' },
        ]"
      >
        <el-select
          style="width: 600px"
          clearable
          v-model="formData.status"
          filterable
        >
          <el-option
            v-for="item in RULE_STATUS_ENUM"
            :key="item.label"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关联业务方法" prop="relBusinessMethods">
        <el-select
          style="width: 600px"
          multiple
          clearable
          v-model="formData.relBusinessMethods"
          filterable
        >
          <el-option
            v-for="item in serviceList"
            :key="item.id"
            :value="item.key"
            :label="item.key + '(' + item.name + ')'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规则说明">
        <el-input
          type="textarea"
          v-model="formData.description"
          style="width: 600px"
          placeholder="请输入规则说明"
          :maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <div style="padding-left: 30px; margin-top: 20px">
      <span style="font-weight: 700">静态规则
      <el-tooltip
          popper-class="custom-popper"
          content="一般用于业务模型新增、修改逻辑输入参数的校验，即入参校验"
          placement="top"
      >
        <i class="el-icon-question" />
      </el-tooltip>
      </span>
      <i class="el-icon-plus" @click="handleAddRuleStaticConfig"></i>
      <el-table
        ref="table"
        class="mt20"
        :data="ruleDetailsList"
        v-loading="loading"
        style="width: 100%"
        current-row-key="id"
        stripe
        border
        highlight-current-row
      >
        <el-table-column prop="" label="规则">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEditStatic(scope.row, scope.$index)"
            >规则详情</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="errorMessage" label="异常信息" />
        <el-table-column prop="actions" label="操作" width="180">
          <template slot-scope="scope">
            <span class="table-actionItem">
              <el-popconfirm
                title="确定要删除该规则吗？"
                placement="top"
                @confirm="handleDeleteStatic(scope.row, scope.$index)"
              >
                <el-button
                  class="link-danger"
                  type="text"
                  slot="reference"
                >删除</el-button
                >
              </el-popconfirm>
            </span>
            <span class="table-actionItem" v-if="scope.$index > 0">
              <el-button
                type="text"
                @click="handleMove(scope.row, 'up', scope.$index, 'static')"
              >上移</el-button
              >
            </span>
            <span
              class="table-actionItem"
              v-if="scope.$index < ruleDetailsList.length - 1"
            >
              <el-button
                type="text"
                @click="handleMove(scope.row, 'down', scope.$index, 'static')"
              >下移</el-button
              >
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div style="padding-left: 30px; margin-top: 30px">
      <span style="font-weight: 700">动态规则</span>
      <el-tooltip
          popper-class="custom-popper"
          content="用于配置实体业务模型数据新增、修改和删除时的数据校验规则"
          placement="top"
      >
        <i class="el-icon-question" />
      </el-tooltip>
      <i class="el-icon-plus" @click="handleAddRuleDynamicConfig"></i>
      <el-table
        ref="table"
        class="mt20"
        :data="dynamicRules"
        v-loading="loading"
        style="width: 100%"
        current-row-key="id"
        stripe
        border
        highlight-current-row
      >
        <el-table-column prop="" label="规则">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEditDynamic(scope.row, scope.$index)"
            >规则详情</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="errorMessage" label="异常信息" />
        <el-table-column prop="actions" label="操作" width="180">
          <template slot-scope="scope">
            <span class="table-actionItem">
              <el-popconfirm
                title="确定要删除该规则吗？"
                placement="top"
                @confirm="handleDeleteDynamic(scope.row, scope.$index)"
              >
                <el-button
                  class="link-danger"
                  type="text"
                  slot="reference"
                >删除</el-button
                >
              </el-popconfirm>
            </span>
            <span class="table-actionItem" v-if="scope.$index > 0">
              <el-button
                type="text"
                @click="handleMove(scope.row, 'up', scope.$index, 'dynamic')"
              >上移</el-button
              >
            </span>
            <span
              class="table-actionItem"
              v-if="scope.$index < dynamicRules.length - 1"
            >
              <el-button
                type="text"
                @click="handleMove(scope.row, 'down', scope.$index, 'dynamic')"
              >下移</el-button
              >
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div slot="footer" class="tr">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
    <RuleStaticConfig
      ref="RuleStaticConfig"
      :modelInfo="modelInfo"
      @ok="handleRuleStaticChange"
    ></RuleStaticConfig>
    <RuleDynamicConfig
      ref="RuleDynamicConfig"
      :modelInfo="modelInfo"
      @ok="handleRuleDynamicChange"
    ></RuleDynamicConfig>
  </el-dialog>
</template>

<script>

import { RULE_STATUS_ENUM } from '@/utils/enum'
import RuleStaticConfig from './RuleStaticConfig'
import RuleDynamicConfig from './RuleDynamicConfig'
import { postModelvalidationrule,putModelvalidationrule } from '@/apis/paas/HmModelValidationRuleController.js'
import { getHmhttprequestdefinitionPageList } from '@/apis/paas/HmHttpRequestDefinitionController.js'
import { cloneDeep } from 'lodash'
export default {
  name: 'RuleForm',
  props: {
    modelInfo: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    RuleStaticConfig,
    RuleDynamicConfig
  },
  data () {
    return {
      RULE_STATUS_ENUM,
      loading: false,
      ruleDetailsList: [], // 静态规则
      dynamicRules: [],
      serviceList: [],
      showVisible: false,
      formData: {}
    }
  },

  computed: {
    isNew () {
      return !this.formData.id
    }
  },

  created () {},

  methods: {
    async addForm (recordData = {}) {
      const record = cloneDeep(recordData)
      this.showVisible = true
      const data = await getHmhttprequestdefinitionPageList({
        pageNo: 1,
        pageSize: 999999,
        modelId: this.modelInfo.id
      })
      this.serviceList = data.data
      this.formData = {
        ...record,
        status: RULE_STATUS_ENUM[0].value
      }
      this.ruleDetailsList = record.ruleDetailsList || []
      this.dynamicRules = record.dynamicRules || []
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    async editForm (recordData = {}) {
      const record = cloneDeep(recordData)
      const data = await getHmhttprequestdefinitionPageList({
        pageNo: 1,
        pageSize: 999999,
        modelId: this.modelInfo.id
      })
      this.serviceList = data.data
      this.showVisible = true
      this.formData = {
        ...record
      }
      this.formData.relBusinessMethods =
        record.relBusinessMethods.match(/\w+/g) || []
      this.ruleDetailsList = record.ruleDetailsList || []
      this.dynamicRules = record.dynamicRules || []
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    handleAddRuleStaticConfig () {
      const dialog = this.$refs.RuleStaticConfig
      dialog.addForm({}, this.ruleDetailsList.length)
    },
    handleAddRuleDynamicConfig () {
      const dialog = this.$refs.RuleDynamicConfig
      dialog.addForm({}, this.dynamicRules.length)
    },
    async submit () {
      try {
        await this.$refs.form.validate()
        if (!this.dynamicRules.length && !this.ruleDetailsList.length) {
          this.$confirm('规则明细不能为空', '', {
            confirmButtonText: '关闭',
            showCancelButton: false,
            type: 'warning'
          })
          return
        }
        const modelId = this.modelInfo.id
        const modelCode = this.modelInfo.code
        let {
          id,
          ruleName,
          ruleCode,
          status,
          relBusinessMethods,
          description
        } = this.formData
        relBusinessMethods && (relBusinessMethods = relBusinessMethods.join(','))
        let params = {}
        let request = null
        if (this.isNew) {
          params = {
            modelId,
            modelCode,
            ruleName,
            ruleCode,
            status,
            relBusinessMethods,
            description
          }
          request = postModelvalidationrule
        } else {
          params = {
            id,
            modelId,
            modelCode,
            ruleName,
            ruleCode,
            relBusinessMethods,
            description
          }
          request = putModelvalidationrule
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === 'string' ? params[key].trim() : params[key]
        }
        params.dynamicRules = this.dynamicRules
        params.ruleDetailsList = this.ruleDetailsList
        request(params).then((res) => {
          this.$message.success('操作成功')
          this.handleCancel()
          this.$emit('ok')
        })
      } catch (error) {
        console.log(error)
      }
    },
    handleCancel () {
      this.showVisible = false
    },
    handleEditStatic (record, index) {
      const dialog = this.$refs.RuleStaticConfig
      dialog.editForm(record, index)
    },
    handleEditDynamic (record, index) {
      const dialog = this.$refs.RuleDynamicConfig
      dialog.editForm(record, index)
    },
    handleRuleStaticChange (ruleData) {
      const index = ruleData.index
      this.$nextTick(() => {
        this.$set(this.ruleDetailsList, index, ruleData)
        this.ruleDetailsList[index] = ruleData
      })
    },
    handleRuleDynamicChange (ruleData) {
      const index = ruleData.index
      const rule = ruleData.ruleData
      this.$nextTick(() => {
        this.$set(this.dynamicRules, index, rule)
        this.dynamicRules[index] = rule
      })
    },
    handleDeleteDynamic (record, index) {
      this.dynamicRules.splice(index, 1)
    },
    handleDeleteStatic (record, index) {
      this.ruleDetailsList.splice(index, 1)
    },
    handleMove (record, direction = 'up', index, type = 'static') {
      let tableData
      if (type === 'dynamic') {
        tableData = this.dynamicRules
      } else {
        tableData = this.ruleDetailsList
      }

      if (direction === 'up') {
        const upDate = tableData[index - 1]
        tableData.splice(index - 1, 1)
        tableData.splice(index, 0, upDate)
      } else {
        const downDate = tableData[index + 1]
        tableData.splice(index + 1, 1)
        tableData.splice(index, 0, downDate)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-icon-plus {
  margin-left: 10px;
  font-size: 16px;
  color: #409eff;
  font-weight: bold;
  cursor: pointer;
  position: relative;
  top: 0px;
}
</style>
